/**
 * @Description: 新建工作分支指令
 * @author Beon
 * @date 2021/1/28
*/
import {Command} from '../types/command';
import {ClassTool} from '../decorators/classTool';
import {OraLoading} from '../decorators/oraLoading';
import {backBranchTypeData, CommitBranchInquirer} from '../inquirer/commitBranchInquirer';
import {backJiraData, JiraInquirer} from '../inquirer/jiraInquirer';
import {LzgitCliFile} from '../utils/lzgitCliFile';
import {BranchOrigin} from '../git/branchOrigin';
import {OtherInquirer} from '../inquirer/otherInquirer';
import {Checkout} from '../git/checkout';
import {MessageDeal} from '../utils/messageDeal';

export class LzBranch implements Command{
	@OraLoading.beProxy
	status: OraLoading // 执行状态
	static BRANCHTYPE: backBranchTypeData
	static JIRADATA: backJiraData
	static baseConfirm = {
	    type: 'confirm',
	    name: 'checkNext',
	    message: ''
	}

	constructor() {
	    this.status.value = '新建工作分支准备';
	}

	/**
	 * 指令运行函数
	 * @param {[String]} arg 参数
	 * @returns {Promise<void>}
	 */
	@ClassTool.saveThis
	async done(arg?: [string]): Promise<void> {
	    if (!await LzBranch.beforeDeal()) {

		    await LzBranch.dealBranchInfo();

		    this.status.value = '新建工作';

		    await LzBranch.checkoutBranch();

	    }

	    this.status.value = '';
	}

	/**
	 * 处理提前判断是否继续执行
	 * @returns {Promise<boolean>}
	 */
	static async beforeDeal(repoPath?: string): Promise<boolean> {
	    const {branchCheck} = LzgitCliFile.getFileData(['branchCheck']);
	    await BranchOrigin.dealBranchMessage(repoPath);

	    if (branchCheck) {
	    	console.log(`当前分支为${BranchOrigin.gitBranch}\n`.debug);
		    return !branchCheck;
	    }

	    this.baseConfirm.message = `当前分支为:${BranchOrigin.gitBranch}，是否确认从该分支开始创建`;

	    const {checkNext} = await OtherInquirer.baseInquirer([this.baseConfirm]) as {checkNext: boolean};

	    return !checkNext;
	}

	/**
	 * 处理新建分支需要的信息
	 * @returns {Promise<void>}
	 */
	static async dealBranchInfo(): Promise<void> {
	    this.BRANCHTYPE = await CommitBranchInquirer.getBranchTypeInquirer();

	    this.JIRADATA = await JiraInquirer.jiraInquirer();
	}

	/**
	 * 创建新的工作分支
	 * @returns {Promise<void>}
	 */
	static async checkoutBranch(repoPath?: string): Promise<void> {
	    const NEWBRANCH = `${this.BRANCHTYPE}‖${typeof this.JIRADATA === 'string' ? this.JIRADATA : this.JIRADATA.join('ˉ')}`;

	    await Checkout.checkNewBranch(MessageDeal.removeSpace(NEWBRANCH), repoPath);
	}
}
